﻿@page "/evd"
@inject IHttpClientFactory httpClientFactory
@using System.Security.Cryptography.X509Certificates
@using System.Security.Cryptography
@using System.Net
@using System.Net.Security
@using System.Security.Authentication
@using System.Text.Json
@using System.Text
@using System.Net.Http.Headers
@using Tool7.Models

<PageTitle>Tool</PageTitle>

<MudText Typo="Typo.h3" GutterBottom="true">Tool</MudText>

<div class="d-flex">
    <MudTextField @bind-Value="userName" Label="UserName" Variant="Variant.Text" Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.LockPerson" />
    <MudTextField @bind-Value="password" Label="Password" Variant="Variant.Text" InputType="@PasswordInput"
                  Adornment="Adornment.End" AdornmentIcon="@PasswordInputIcon" OnAdornmentClick="ButtonTestclick" AdornmentAriaLabel="Show Password" />
    <MudButton Disabled="@_processing" OnClick="ProcessSomething" Variant="Variant.Filled" Color="Color.Primary">
        @if (_processing)
        {
            <MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
            <MudText Class="ms-2">Processing</MudText>
        }
        else
        {
            <MudText>login</MudText>
        }
    </MudButton>
</div>


@code {
    private string userName = "likeshan";
    private string password = "Sfqd@20220428";
    private bool _processing = false;

    bool isShow;
    InputType PasswordInput = InputType.Password;
    string PasswordInputIcon = Icons.Material.Filled.VisibilityOff;

    void ButtonTestclick()
    {
        @if (isShow)
        {
            isShow = false;
            PasswordInputIcon = Icons.Material.Filled.VisibilityOff;
            PasswordInput = InputType.Password;
        }
        else
        {
            isShow = true;
            PasswordInputIcon = Icons.Material.Filled.Visibility;
            PasswordInput = InputType.Text;
        }
    }

    async Task ProcessSomething()
    {
        string loginUrl = $"/login/";
        string authenticateUrl = $"/authenticate/";

        try
        {

            // 创建 HttpClient 并发送请求
            using (var httpClient = httpClientFactory.CreateClient("yunwei"))
            {
                httpClient.DefaultRequestVersion = new Version(2, 0);
                httpClient.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact;
                var authRequest = new HttpRequestMessage(HttpMethod.Post, authenticateUrl);
                authRequest.Headers.Add("Referer", $"{httpClient.BaseAddress}{loginUrl.TrimStart('/')}");
                authRequest.Headers.Add("Accept", "application/json; charset=UTF-8");
                authRequest.Headers.Add("Host", "yunwei.beijing.gwhome:34443");
                authRequest.Headers.Add("Origin", "https:yunwei.beijing.gwhome:34443");
                authRequest.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:141.0) Gecko/20100101 Firefox/141.0");

                // 发送 GET 请求
                var response = await httpClient.GetAsync(loginUrl);

                // var html = await response.Content.ReadAsStringAsync();
                // Console.WriteLine(html);

                // request.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Response Status: Success");

                    // 获取响应头中的 Set-Cookie 字段
                    if (response.Headers.TryGetValues("Set-Cookie", out var cookieValues))
                    {
                        foreach (var cookie in cookieValues)
                        {
                            Console.WriteLine("Received Set-Cookie: " + cookie);
                            authRequest.Headers.Add("Cookie", cookie);
                        }
                    }

                    // 3. 获取 csrftoken（从 Cookie 中）
                    // HttpClient 没有 GetCookies 方法，需手动解析 Set-Cookie
                    var csrfCookie = cookieValues?.FirstOrDefault(c => c.Contains("csrftoken="));
                    if (csrfCookie != null)
                    {
                        var csrfValue = csrfCookie.Split(';').FirstOrDefault(x => x.Trim().StartsWith("csrftoken="));
                        if (csrfValue != null)
                        {
                            var token = csrfValue.Substring("csrftoken=".Length);
                            authRequest.Headers.Add("X-CSRFToken", token);
                        }
                    }

                    // 构建 Form 数据
                    var collection = new List<KeyValuePair<string, string>>();
                    collection.Add(new("username", userName));
                    collection.Add(new("password", password));
                    var content = new FormUrlEncodedContent(collection);
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                    authRequest.Content = content;
                    // 显式设置 Content-Type
                    

                    var postResponse = await httpClient.SendAsync(authRequest);
                    Console.WriteLine(postResponse.Version);
                    // 6. 处理响应
                    if (postResponse.IsSuccessStatusCode)
                    {
                        var responseBody = await postResponse.Content.ReadAsByteArrayAsync();
                        var jsonStr = Encoding.UTF8.GetString(responseBody);
                        Console.WriteLine("请求成功！");
                        Console.WriteLine($"状态码: {postResponse.StatusCode}");
                        Console.WriteLine($"响应内容: {jsonStr}");
                    }
                    else
                    {
                        Console.WriteLine($"请求失败，状态码: {postResponse.StatusCode}");
                        Console.WriteLine($"原因: {postResponse.ReasonPhrase}");
                    }
                }
                else
                {
                    Console.WriteLine($"Error: {response.StatusCode}");
                }
            }
        }
        catch (HttpRequestException httpEx)
        {
            // 专门捕获 HTTP 层异常，可能包含内部异常
            Console.WriteLine($"HTTP 请求异常: {httpEx.Message}");
            if (httpEx.InnerException != null)
            {
                Console.WriteLine($"内部异常: {httpEx.InnerException.Message}");
                // 这里可能会看到 "The credentials supplied to the package were not recognized"
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生错误: {ex.Message}，{ex.InnerException?.Message}，{ex.StackTrace}");
            if (ex is CryptographicException cryptoEx)
            {
                Console.WriteLine($"加密错误详情: {cryptoEx.Message}");
            }
        }
        finally
        {
            _processing = false;
        }
    }

}